const { get, run, all } = require('../config/db');
const bcrypt = require('bcrypt');

class User {
  // 创建用户
  static async create(username, email, password) {
    try {
      // 生成密码哈希
      const saltRounds = 10;
      const passwordHash = await bcrypt.hash(password, saltRounds);
      
      // 插入用户记录
      const result = await run(
        'INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)',
        [username, email, passwordHash]
      );
      
      return { id: result.id, username, email };
    } catch (error) {
      console.error('创建用户失败:', error);
      throw error;
    }
  }
  
  // 通过用户名查找用户
  static async findByUsername(username) {
    try {
      const user = await get(
        'SELECT * FROM users WHERE username = ?',
        [username]
      );
      
      return user || null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }
  
  // 通过邮箱查找用户
  static async findByEmail(email) {
    try {
      const user = await get(
        'SELECT * FROM users WHERE email = ?',
        [email]
      );
      
      return user || null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }
  
  // 通过ID查找用户
  static async findById(id) {
    try {
      const user = await get(
        'SELECT id, username, email, created_at, is_admin FROM users WHERE id = ?',
        [id]
      );
      
      return user || null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }
  
  // 验证密码
  static async verifyPassword(user, password) {
    try {
      return await bcrypt.compare(password, user.password_hash);
    } catch (error) {
      console.error('密码验证失败:', error);
      throw error;
    }
  }
  
  // 更新最后登录时间
  static async updateLastLogin(id) {
    try {
      await run(
        'UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?',
        [id]
      );
      return true;
    } catch (error) {
      console.error('更新登录时间失败:', error);
      throw error;
    }
  }
}

module.exports = User;
